package com.treasure.web.listener;

import com.treasure.infrastructure.model.event.ConversationEvent;
import com.treasure.infrastructure.model.po.ModelUsageDetails;
import com.treasure.infrastructure.repository.dao.mapper.ModelUsageDetailsMapper;
import com.treasure.web.service.IAiRobotService;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;


/**
 * @author sunhongmin
 * @date 2024/1/14 10:22
 * @description
 */
@Component
@RequiredArgsConstructor
public class ModelUsageEventListener {

    private final ModelUsageDetailsMapper modelUsageDetailsMapper;
    private final IAiRobotService aiRobotService;

    @EventListener
    @Async
    public void onApplicationEvent(@NotNull ConversationEvent conversationEvent) {
        ModelUsageDetails modelUsageDetails = new ModelUsageDetails();
        modelUsageDetails.setCorpId(conversationEvent.getCorpId());
        modelUsageDetails.setUserId(conversationEvent.getUserId());
        modelUsageDetails.setModel(conversationEvent.getModel());
        modelUsageDetails.setTokens(conversationEvent.getInputTokens() + conversationEvent.getOutputTokens());
        modelUsageDetails.setCreateTime(conversationEvent.getCreateTime());
        modelUsageDetails.setRobotId(aiRobotService.getCorpDefaultRobotId(conversationEvent.getCorpId()));
        modelUsageDetails.setManufacturer(conversationEvent.getManufacturer());
        modelUsageDetailsMapper.insert(modelUsageDetails);
    }
}
